package com.easy.common.utils.mail;

import com.alicp.jetcache.Cache;
import com.alicp.jetcache.anno.CreateCache;
import com.easy.common.constant.RegularExpression;
import com.easy.common.core.R;
import com.easy.common.core.domain.entity.EmailBody;
import com.easy.common.mq.MessageRocketProducer;
import com.easy.common.utils.VerifyCodeUtils;
import com.easy.common.utils.uuid.UUID;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * 邮件发送处理工具类
 *
 * @author RuoYu
 * @date 2022/11/18
 */
@Component
public class MailUtils {

    @CreateCache(area = "email", name = "ord_user_", expire = 300, timeUnit = TimeUnit.SECONDS)
    private Cache<String, String> jetCache;

    @Autowired
    private MessageRocketProducer messageRocketProducer;

    /**
     * 邮箱
     *
     * @param mail 邮箱号码
     * @return {@link R}
     */
    public R sendMail(String mail) {
        // 1.邮箱地址书写是否正确
        if (mail.matches(RegularExpression.MAIL_PATTERN)) {
            // 2.判断缓存区中有无缓存（验证码是否已发）
            if (!StringUtils.isNoneEmpty(jetCache.get(mail))) {
                // 随机生成验证码
                String captcha = VerifyCodeUtils.getCode(mail);
                String id = UUID.fastUUID().toString();
                EmailBody emailBody = new EmailBody("0",id, mail, captcha);

                String s = messageRocketProducer.sendMessage(emailBody);

                //3.验证码放入缓存
                jetCache.put(mail, captcha);
                return R.success("验证码发送成功，请到邮箱进行查收");
            } else {
                return R.success("验证码已发送，稍等片刻！");
            }
        }
        return R.error("请输入正确的邮箱号！！！");
    }

}
